package cn.yuanqiao.system.service.impl;

import java.util.Collection;
import java.util.List;
import javax.annotation.PostConstruct;

import cn.yuanqiao.common.service.RedisService;
import cn.yuanqiao.common.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import cn.yuanqiao.common.annotation.DataSource;
import cn.yuanqiao.common.constant.CacheConstants;
import cn.yuanqiao.common.constant.UserConstants;
import cn.yuanqiao.common.core.redis.RedisCache;
import cn.yuanqiao.common.core.text.Convert;
import cn.yuanqiao.common.enums.DataSourceType;
import cn.yuanqiao.common.exception.ServiceException;
import cn.yuanqiao.common.utils.StringUtils;
import cn.yuanqiao.system.domain.SysConfig;
import cn.yuanqiao.system.mapper.SysConfigMapper;
import cn.yuanqiao.system.service.ISysConfigService;

/**
 * 参数配置 服务层实现
 * 
 * @author ruoyi
 */
@Service
public class SysConfigServiceImpl implements ISysConfigService
{
    @Autowired
    private SysConfigMapper configMapper;

    @Autowired
    private RedisService redisService;

    /**
     * 项目启动时，初始化参数到缓存
     */
    /*@PostConstruct
    public void init()
    {
        loadingConfigCache();
    }*/

    /**
     * 查询参数配置信息
     *
     * @param configId 参数配置ID
     * @return 参数配置信息
     */
    @Override
    public SysConfig selectConfigById(String configId)
    {
        SysConfig config = new SysConfig();
        config.setConfigId(Long.valueOf(configId));
        return configMapper.selectConfig(config);
    }

    /**
     * 根据键名查询参数配置信息
     *
     * @param configKey 参数key
     * @return 参数键值
     */
    @Override
    public String selectConfigByKey(String configKey)
    {
        String tenantCode = SecurityUtils.getTenantCode();
        String configValue = Convert.toStr(redisService.getCacheObject(getCacheKey(tenantCode,configKey)));
        if (StringUtils.isNotEmpty(configValue))
        {
            return configValue;
        }
        SysConfig config = new SysConfig();
        config.setConfigKey(configKey);
        config.setTenantCode(tenantCode);
        config.setConfigType("Y");
        SysConfig retConfig = configMapper.selectConfig(config);
        if (StringUtils.isNotNull(retConfig))
        {
            redisService.setCacheObject(getCacheKey(tenantCode,configKey), retConfig.getConfigValue());
            return retConfig.getConfigValue();
        }
        return StringUtils.EMPTY;
    }


    /**
     * 查询参数配置列表
     *
     * @param config 参数配置信息
     * @return 参数配置集合
     */
    @Override
    public List<SysConfig> selectConfigList(SysConfig config)
    {
        return configMapper.selectConfigList(config);
    }

    /**
     * 新增参数配置
     *
     * @param config 参数配置信息
     * @return 结果
     */
    @Override
    public int insertConfig(SysConfig config)
    {
        int row = configMapper.insertConfig(config);
        if (row > 0)
        {
            redisService.setCacheObject(getCacheKey(config.getTenantCode(),config.getConfigKey()), config.getConfigValue());
        }
        return row;
    }

    /**
     * 修改参数配置
     *
     * @param config 参数配置信息
     * @return 结果
     */
    @Override
    public int updateConfig(SysConfig config)
    {
        SysConfig temp = configMapper.selectConfigById(String.valueOf(config.getConfigId()));
        if (!StringUtils.equals(temp.getConfigKey(), config.getConfigKey()))
        {
            redisService.deleteObject(getCacheKey(temp.getTenantCode(),temp.getConfigKey()));
        }

        int row = configMapper.updateConfig(config);
        if (row > 0)
        {
            redisService.setCacheObject(getCacheKey(temp.getTenantCode(),config.getConfigKey()), config.getConfigValue());
        }
        return row;
    }

    /**
     * 批量删除参数信息
     *
     * @param configIds 需要删除的参数ID
     */
    @Override
    public void deleteConfigByIds(String[] configIds)
    {
        for (String configId : configIds)
        {
            SysConfig config = selectConfigById(configId);
            if (StringUtils.equals(UserConstants.YES, config.getConfigType()))
            {
                throw new ServiceException(String.format("内置参数【%1$s】不能删除 ", config.getConfigKey()));
            }
            configMapper.deleteConfigById(configId);
            redisService.deleteObject(getCacheKey(config.getTenantCode(),config.getConfigKey()));
        }
    }

    /**
     * 加载参数缓存数据
     */
    @Override
    public void loadingConfigCache()
    {
        SysConfig sysConfig = new SysConfig();
        sysConfig.setTenantCode(SecurityUtils.getTenantCode());
        sysConfig.setConfigType("Y");
        List<SysConfig> configsList = configMapper.selectConfigList(sysConfig);
        for (SysConfig config : configsList)
        {
            redisService.setCacheObject(getCacheKey(config.getTenantCode(),config.getConfigKey()), config.getConfigValue());
        }
    }

    /**
     * 清空参数缓存数据
     */
    @Override
    public void clearConfigCache()
    {
        String tenantCode = SecurityUtils.getTenantCode();
        Collection<String> keys;
        if(StringUtils.isNotEmpty(tenantCode)){
            keys = redisService.keys(tenantCode+"_"+CacheConstants.SYS_CONFIG_KEY + "*");
        }else {
            keys = redisService.keys(CacheConstants.SYS_CONFIG_KEY + "*");
        }
        redisService.deleteObject(keys);
    }

    /**
     * 重置参数缓存数据
     */
    @Override
    public void resetConfigCache()
    {
        clearConfigCache();
        loadingConfigCache();
    }

    /**
     * 校验参数键名是否唯一
     *
     * @param config 参数配置信息
     * @return 结果
     */
    @Override
    public boolean checkConfigKeyUnique(SysConfig config)
    {
        String configId = StringUtils.isNull(config.getConfigId()) ? "-1" : String.valueOf(config.getConfigId());
        String tenantCode = SecurityUtils.getTenantCode();
        SysConfig info = configMapper.checkConfigKeyUnique(config.getConfigKey(),tenantCode);
        if (StringUtils.isNotNull(info) && !info.getConfigId().equals(configId))
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    @Override
    public String selectConfigByKeyTenantCode(String configKey, String tenantCode) {
        String configValue = Convert.toStr(redisService.getCacheObject(getCacheKey(tenantCode,configKey)));
        if (StringUtils.isNotEmpty(configValue))
        {
            return configValue;
        }
        SysConfig config = new SysConfig();
        config.setConfigKey(configKey);
        config.setTenantCode(tenantCode);
        config.setConfigType("Y");
        SysConfig retConfig = configMapper.selectConfig(config);
        if (StringUtils.isNotNull(retConfig))
        {
            redisService.setCacheObject(getCacheKey(tenantCode,configKey), retConfig.getConfigValue());
            return retConfig.getConfigValue();
        }
        return StringUtils.EMPTY;
    }

    @Override
    public void endInit() {
        String tenantCode = SecurityUtils.getTenantCode();
        SysConfig config = new SysConfig();
        config.setConfigKey("INIT_SYSTEM");
        config.setTenantCode(tenantCode);
        config.setConfigType("Y");
        SysConfig retConfig = configMapper.selectConfig(config);
        retConfig.setConfigValue("false");
        updateConfig(retConfig);
    }

    /**
     * 设置cache key
     *
     * @param configKey 参数键
     * @return 缓存键key
     */
    private String getCacheKey(String tenantCode,String configKey)
    {
        if(StringUtils.isNotEmpty(tenantCode)){
            return tenantCode+"_"+CacheConstants.SYS_CONFIG_KEY + configKey;
        }else {
            return CacheConstants.SYS_CONFIG_KEY + configKey;
        }
    }
}
